//
//  KeHuSouSuoViewController.m
//  JuBoCRM
//
//  Created by iMac on 2024/2/4.
//  Copyright © 2024 iningKe. All rights reserved.
//

#import "KeHuSouSuoViewController.h"
#import "KeHuListTableViewCell.h"
#import "GongHaiListTableViewCell.h"
#import "KeHuXiangQingViewController.h"
#import "AlertRemindView.h"
#import "XinJianKeHuViewController.h"
#import "GongHaiKeHuXiangQingViewController.h"
@interface KeHuSouSuoViewController ()
<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,UITextFieldDelegate>{
    int page;
    NSMutableArray *dataSource;
}
@property (weak, nonatomic) IBOutlet TPKeyboardAvoidingTableView *mainTableView;
@property (weak, nonatomic) IBOutlet UITextField *searchTextField;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;
@end

@implementation KeHuSouSuoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.customNavBar.title = @"搜索";
    
    _topSpace.constant = NavaBarHeight;
    [_mainTableView registerNib:[UINib nibWithNibName:@"KeHuListTableViewCell" bundle:nil] forCellReuseIdentifier:@"KeHuListTableViewCell"];
    [_mainTableView registerNib:[UINib nibWithNibName:@"GongHaiListTableViewCell" bundle:nil] forCellReuseIdentifier:@"GongHaiListTableViewCell"];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self downRefresh];
    }];

    _mainTableView.mj_header = header;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self upRefresh];
    }];
    _mainTableView.mj_footer = footer;
    page = 1;
    [self getInfoFromServer];
    
    [_searchTextField becomeFirstResponder];
    
    // 创建一个手势识别器
       UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]
                                              initWithTarget:self
                                              action:@selector(dismissKeyboard:)];
       
       // 设置手势识别器不取消视图中的触摸
       tapGesture.cancelsTouchesInView = NO;
//       tapGesture.delaysTouchesBegan = YES;
       // 将手势识别器添加到view
       [self.view addGestureRecognizer:tapGesture];
}

- (void)dismissKeyboard:(UITapGestureRecognizer *)recognizer {
    CGPoint location = [recognizer locationInView:self.mainTableView];
    NSIndexPath *indexPath = [self.mainTableView indexPathForRowAtPoint:location];

    if (!indexPath) {
        // 点击的不是UITableViewCell，收起键盘
        [self.view endEditing:YES];
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    [self downRefresh];
    return YES;
}

//上拉刷新
- (void)upRefresh {
    page++;
    [self getInfoFromServer];
}

//下拉刷新
- (void)downRefresh {
    page = 1;
    [self getInfoFromServer];
}

- (void)getInfoFromServer{
    
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:[NSString stringWithFormat:@"%d",page] forKey:@"page"];
    [paraDic setValue:@10 forKey:@"limit"];
    [paraDic setValue:_searchTextField.text forKey:@"search"];
    NSString *url = @"/crmCustomer/queryPageList";
    if (_type.integerValue == 2) {
        url = @"/crmCustomerAll/queryPageList";
        [paraDic setValue:@"2" forKey:@"label"];
    }else{
        [paraDic setValue:@"2" forKey:@"type"];
    }
    if(_isGongHai){
        [paraDic setValue:@"9" forKey:@"type"];
        [paraDic setValue:_poolId forKey:@"poolId"];
        url = @"/crmCustomerPool/queryPageList";
    }
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:url andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if (!error) {
            NSLog(@"info:%@",info);
            NSArray *array = [[info objectForKey:@"data"] objectForKey:@"list"];
            if (page == 1) {
                if ([array count]> 9) {
                    dataSource = [NSMutableArray arrayWithArray:array];
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshing];
                }else {
                    dataSource = [NSMutableArray arrayWithArray:array];
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshingWithNoMoreData];
                    if(dataSource.count == 0){
                        _mainTableView.mj_footer.hidden = YES;
                    }else{
                        _mainTableView.mj_footer.hidden = NO;
                    }
                }
            }else {
                if ([array count]> 9) {
                    [dataSource addObjectsFromArray:array];
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshing];
                }else {
                    NSArray *tempArray = array;
                    if (tempArray.count > 0) {
                        [dataSource addObjectsFromArray:tempArray];
                    }
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            
            [_mainTableView reloadData];
            
            
        }else {
            [_mainTableView.mj_header endRefreshing];
            [_mainTableView.mj_footer endRefreshing];
        }
    }];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_isGongHai){
        return 182;
    }
    if (_type.integerValue == 2) {
        return 260-52;
    }
    return 260;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_isGongHai){
        GongHaiListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GongHaiListTableViewCell"];
        NSDictionary *dataDic = dataSource[indexPath.row];
        cell.nameLabel.text = GetHandleString(dataDic, @"customerName");
        cell.phoneLabel.text = GetHandleString(dataDic, @"mobile");
        cell.statusLabel.text = GetHandleString(dataDic, @"level");
        cell.fuZeRenLabel.text = GetHandleString(dataDic, @"lastTime");
        cell.manageClickBlock = ^{
    //        领取
            [self.view endEditing:YES];
            [self piLiangLingQuWithUserId:@[GetHandleString(dataDic, @"customerId")] andPoolId:[NSString stringWithFormat:@"%ld",indexPath.row]];
            
        };
        return cell;
    }
    KeHuListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KeHuListTableViewCell"];
    NSDictionary *dataDic = dataSource[indexPath.row];
    cell.nameLabel.text = GetHandleString(dataDic, @"customerName");
    cell.phoneLabel.text = GetHandleString(dataDic, @"mobile");
    cell.fuZeRenLabel.text = GetHandleString(dataDic, @"ownerUserName");
    cell.genJinShiJianLabel.text = GetHandleString(dataDic, @"lastTime");
    cell.juLiGongHaiLabel.text = [NSString stringWithFormat:@"%ld天",[GetHandleString(dataDic, @"poolDay") integerValue]];
    cell.zhuangTaiLabel.text = GetHandleString(dataDic, @"level");
    
    cell.manageClickBlock = ^(NSInteger index) {
        [self.view endEditing:YES];
        if(index == 101){
            if([GetHandleString(dataDic, @"mobile") length] > 0){
                [ZZPUtils telephoneForAppWithNum:GetHandleString(dataDic, @"mobile")];
            }else{
                [ZZPUtils showWarning:@"暂无联系方式"];
            }
        }else{
            XinJianKeHuViewController *gongHai = [[XinJianKeHuViewController alloc] init];
            gongHai.customerId = GetHandleString(dataDic, @"customerId");
            [self.navigationController pushViewController:gongHai animated:YES];
        }
    };
    
    if (_type.intValue == 2) {
        //客户全览
        cell.jieDuanView.hidden = YES;
        cell.jieDuanViewHeight.constant = 0;
        cell.fuZeRenRemindLabel.text = @"来源";
        cell.genJinShiJianRedminLabel.text = @"负责人";
        cell.jinRuRemindLabel.text = @"跟进时间";
        cell.nameLabel.text = GetHandleString(dataDic, @"customerName");
        cell.phoneLabel.text = GetHandleString(dataDic, @"mobile");
        cell.fuZeRenLabel.text = GetHandleString(dataDic, @"fieldMasduv");
        cell.genJinShiJianLabel.text = GetHandleString(dataDic, @"ownerUserName");
        cell.juLiGongHaiLabel.text = GetHandleString(dataDic, @"lastTime");
        cell.zhuangTaiLabel.text = GetHandleString(dataDic, @"level");
        
    }else{
        cell.jieDuanView.hidden = NO;
        cell.jieDuanViewHeight.constant = 52;
        cell.fuZeRenRemindLabel.text = @"负责人";
        cell.genJinShiJianRedminLabel.text = @"跟进时间";
        cell.jinRuRemindLabel.text = @"距进入公海";
        cell.nameLabel.text = GetHandleString(dataDic, @"customerName");
        cell.phoneLabel.text = GetHandleString(dataDic, @"mobile");
        cell.fuZeRenLabel.text = GetHandleString(dataDic, @"ownerUserName");
        cell.genJinShiJianLabel.text = GetHandleString(dataDic, @"lastTime");
        cell.juLiGongHaiLabel.text = [NSString stringWithFormat:@"%ld天",[GetHandleString(dataDic, @"poolDay") integerValue]];
        cell.zhuangTaiLabel.text = GetHandleString(dataDic, @"level");
    }
    
    return cell;
}


//批量领取
- (void)piLiangLingQuWithUserId:(NSArray *)userList andPoolId:(NSString *)currentIndex{
    
    if(userList.count == 0){
        [ZZPUtils showWarning:@"请先选择要领取的客户"];
        return;
    }
    
    AlertRemindView *view = [AlertRemindView view];
    [ZZPUtils showAlertViewWithView:view andController:self];
    view.manageClickBlock = ^(NSInteger index) {
        [self dismissViewControllerAnimated:YES completion:^{
            if(index == 102){
    //            确定
                NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
                [paraDic setValue:userList forKey:@"ids"];
                [paraDic setValue:_poolId forKey:@"poolId"];
                [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/crmCustomer/receiveByIds" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
                    if(!error){
                        if([currentIndex length] > 0){
                            [dataSource removeObjectAtIndex:[currentIndex integerValue]];
                            [UIView performWithoutAnimation:^{
                                [_mainTableView reloadData];
                            }];
                        }
                        [self shiFouLingQuChengGong:YES];
                    }else{
                        [self shiFouLingQuChengGong:NO];
                    }
                }];
            }
        }];
    };
}

//是否领取成功
- (void)shiFouLingQuChengGong:(BOOL)isSuccess{
    AlertRemindView *view = [AlertRemindView view];
    [ZZPUtils showAlertViewWithView:view andController:self];
    view.leftButton.hidden = YES;
    view.rightButton.hidden = YES;
    view.centerButton.hidden = NO;
    if(isSuccess){
        view.topImage.image = LocalImagePath(@"公海领取弹窗成功");
        view.titleLabel.text = @"领取成功";
        view.contentLabel.text = @"恭喜领取成功！";
    }else{
        view.topImage.image = LocalImagePath(@"公海领取弹窗失败");
        view.titleLabel.text = @"领取失败";
        view.contentLabel.text = @"超过库容，领取失败";
    }
    view.manageClickBlock = ^(NSInteger index) {
        [self dismissViewControllerAnimated:YES completion:nil];
    };
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_isGongHai){
        GongHaiKeHuXiangQingViewController *xiangQing = [[GongHaiKeHuXiangQingViewController alloc] init];
        NSDictionary *dataDic = dataSource[indexPath.row];
        xiangQing.customerId = GetHandleString(dataDic, @"customerId");
        xiangQing.poolId = GetHandleString(dataDic, @"poolId");
        xiangQing.manageClickResultBlock = ^(NSInteger result) {
            [self downRefresh];
        };
        [self pushViewController:xiangQing];
        return;
    }
    
    
    if (_type.intValue == 2) {
        NSDictionary *dataDic = dataSource[indexPath.row];
        if ([GetHandleString(dataDic, @"ownerUserId") length] == 0) {
            GongHaiKeHuXiangQingViewController *xiangQing = [[GongHaiKeHuXiangQingViewController alloc] init];
            xiangQing.customerId = GetHandleString(dataDic, @"customerId");
            xiangQing.poolId = GetHandleString(dataDic, @"pool");
            xiangQing.manageClickResultBlock = ^(NSInteger result) {
                [self downRefresh];
            };
            [self pushViewController:xiangQing];
        }else{
            KeHuXiangQingViewController *xiangQing = [[KeHuXiangQingViewController alloc] init];
            NSDictionary *dataDic = dataSource[indexPath.row];
            xiangQing.customerId = GetHandleString(dataDic, @"customerId");
            xiangQing.juLiGongHaiNum = GetHandleString(dataDic, @"poolDay");
            xiangQing.shiBuShiZongLanKeHu = YES;
            xiangQing.manageClickResultBlock = ^(NSInteger result) {
                [self downRefresh];
            };
            [self pushViewController:xiangQing];
        }
        return;
    }
    
    KeHuXiangQingViewController *xiangQing = [[KeHuXiangQingViewController alloc] init];
    NSDictionary *dataDic = dataSource[indexPath.row];
    xiangQing.customerId = GetHandleString(dataDic, @"customerId");
    xiangQing.juLiGongHaiNum = GetHandleString(dataDic, @"poolDay");
    [self pushViewController:xiangQing];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView{
    return -90;
}

-(UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"暂无搜索"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"暂无搜索~"attributes: @{NSFontAttributeName: [UIFont systemFontOfSize:16],NSForegroundColorAttributeName: rgba(163, 168, 185, 1)}];
    return string;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
